const { Admin, School } = require("../model");
const express = require("express");
const router = express.Router();

//注销
router.post("/delete", async (q, s) => {
  const res = await Admin.deleteOne(q.body); // 删除第一个匹配的
  s.send({
    success: true,
    data: res,
  });
});


// 注册 - 登录
router.post("/login", async (q, s) => {
  const doc = await Admin.findOne(q.body); // 返回找到的第一个
  if (doc) {
    s.send({
      msg: "登录成功",
      success: true,
      data: doc,
    });
  } else {
    s.send({
      msg: "登录失败",
      success: false,
      data: [],
    });
  }
});

// 修改密码
router.post("/edit", async (q, s) => {
  const doc = await Admin.findOne({ account: q.body.account }); // 返回找到的第一个
  if (doc) {
    if (doc.password === q.body.oldPwd) {
      doc.password = q.body.newPwd;
      const res = await doc.save();
      s.send({
        msg: "修改成功",
        success: true,
        data: res,
      });
    } else {
      s.send({
        msg: "原密码错误",
        success: false,
        data: {},
      });
    }
  } else {
    s.send({
      msg: "修改失败",
      success: false,
      data: [],
    });
  }
});

// 填写增加一个学校
router.post("/addSchool", async (q, s) => {
  const doc = new School(q.body);
  let res = await doc.save();
  s.send({
    msg: "增加成功",
    success: true,
    data: res,
  });
});

// 编辑单个学校
router.post("/editSchool", async (q, s) => {
  const id = q.body.id;
  delete q.body.id;
  const doc = await School.findByIdAndUpdate(id, q.body); // 参数是查询参数，精确匹配，结果是匹配的数组
  s.send({
    msg: "更新成功",
    success: true,
    data: doc,
  });
});


module.exports = router;